package end.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import redis.clients.jedis.Jedis;
import end.bean.Album;
import end.bean.Chapter;
import end.ser.AlbumSER;
import end.ser.ChapterSER;
import end.util.jedis.JedisPoolUtils;

/**
 * 
 * AlbumController.java 2016-6-27
 * 
 * Copyright zhaocj Inc. All rights reserved. Love Me Like Love Justin Bieber
 */
@Controller
@RequestMapping("/album/")
public class AlbumForController {
	private final static Logger logger = LogManager
			.getLogger(AlbumForController.class);

	@Autowired
	private AlbumSER<Album> albumSER;
	@Autowired
	private ChapterSER<Chapter> chapterSER;

	public ChapterSER<Chapter> getChapterSER() {
		return chapterSER;
	}

	public void setChapterSER(ChapterSER<Chapter> chapterSER) {
		this.chapterSER = chapterSER;
	}

	public AlbumSER<Album> getAlbumSER() {
		return albumSER;
	}

	public void setAlbumSER(AlbumSER<Album> albumSER) {
		this.albumSER = albumSER;
	}

	@RequestMapping("queryAlbumsByPage")
	public @ResponseBody
	Map<String, Object> queryByPage(Integer page, Integer rows, String sort,
			String order, HttpSession session) throws Throwable {
		Album album = new Album();
		album.getPageUtil().setPaging(true);
		album.getPageUtil().setOrderByCondition(sort);
		album.getPageUtil().setQueryCondition(order);
		album.getPageUtil().setPageOffset((page - 1) * rows);
		album.getPageUtil().setPageSize(rows);
		album.setUseStatus('0');
		List<Album> beans = albumSER.selectByBean(album);
		Map<String, Object> rets = new HashMap<String, Object>();
		rets.put("total", albumSER.selectByBeanCount(album));
		rets.put("rows", beans);
		return rets;
	}

	@RequestMapping("drop")
	public @ResponseBody
	boolean dropAlbums(Integer drop) throws Exception {
		Chapter chapter = new Chapter();
		chapter.getAlbum().setId(drop);
		chapterSER.deleteByBean(chapter);
		albumSER.deleteByPrimaryKey(drop);
		return true;
	}

	@RequestMapping("insert")
	public @ResponseBody
	boolean insertAlbum(Album album, MultipartFile thumbnailImg,
			HttpSession session) throws Exception {
		album.setUseStatus('0');
		album.setCreateDate(new Date());
		albumSER.insert(album);
		ServletContext context = session.getServletContext();
		if (!new File(context.getRealPath("/static/file/album/"
				+ album.getTitle() + "/icon")).exists()) {
			FileUtils.forceMkdir(new File(context
					.getRealPath("/static/file/album/" + album.getTitle()
							+ "/icon")));
		}
		String realPath = context.getRealPath("/static/file/album/"
				+ album.getTitle() + "/icon");
		if (!thumbnailImg.isEmpty()) {
			String suffix = thumbnailImg.getOriginalFilename().substring(
					thumbnailImg.getOriginalFilename().lastIndexOf("."));
			thumbnailImg.transferTo(new File(realPath + "/" + album.getId()
					+ suffix));
			album.setThumbnail(album.getId() + suffix);
		} else {
			album.setThumbnail("NOIMAGE");
		}
		albumSER.updateByPrimaryKey(album);
		return true;
	}

	@RequestMapping("modify")
	public @ResponseBody
	boolean modifyAlbum(Album album, MultipartFile thumbnailImg,
			HttpSession session, String thumbnailChangeFlag) throws Exception {
		ServletContext context = session.getServletContext();
		String realPath = context.getRealPath("/static/file/album/"
				+ album.getTitle() + "/icon");
		// 如果上传文件框有动静了
		if (thumbnailChangeFlag.equals("ALCHANGE")) {
			if (!thumbnailImg.isEmpty()) {
				// 如果上传了照片 如果先前有专辑照片存在的话 先删掉
				if (!album.getThumbnail().equals("NOIMAGE")) {
					FileUtils.forceDelete(new File(realPath + "/"
							+ album.getThumbnail()));
				}
				String suffix = thumbnailImg.getOriginalFilename().substring(
						thumbnailImg.getOriginalFilename().lastIndexOf("."));
				thumbnailImg.transferTo(new File(realPath + "/" + album.getId()
						+ suffix));
				album.setThumbnail(album.getId() + suffix);
			} else {
				// 如果没有上传图片 并且之前有图片的话 删除服务器的图片
				if (!album.getThumbnail().equals("NOIMAGE")) {
					FileUtils.forceDelete(new File(realPath + "/"
							+ album.getThumbnail()));
					album.setThumbnail("NOIMAGE");
				}
			}
		}
		albumSER.updateByPrimaryKey(album);
		return true;
	}

	@RequestMapping("queryChart")
	public @ResponseBody
	Map<String, Object> queryChart(String[] albumArr) throws Exception {
		Map<String, Object> rets = new HashMap<String, Object>();
		Jedis jedis = JedisPoolUtils.getJedis();
		jedis.select(6);
		List<Integer> chartY = new ArrayList<Integer>();
		List<String> chartX = new ArrayList<String>();
		for (String string : albumArr) {
			chartX.add(string.substring(string.indexOf("+_+") + 3,
					string.length()));
			if (jedis.get("album:" + string) != null) {
				chartY.add(Integer.parseInt(jedis.get("album:" + string)));
			} else {
				chartY.add(0);
			}
		}
		rets.put("chartX", chartX);
		rets.put("chartY", chartY);
		JedisPoolUtils.close(jedis);
		return rets;
	}
}
